package xyz.ibenben.zhongdian.common.configure;

import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;
import xyz.ibenben.zhongdian.common.exception.ExceptionEnum;
import xyz.ibenben.zhongdian.common.exception.MyException;

import java.util.Properties;

/**
 * Mybatis配置
 *
 * @author chenjian
 * @since 2017年7月26日下午6:30:31
 */
@Configuration
@EnableTransactionManagement
public class MyBatisConfig implements TransactionManagementConfigurer {
    /* 配置类型别名 */
    @Value("${mybatis.type-aliases-package}")
    private String typeAliasesPackage;

    /* typeHandlersPackage */
    @Value("${mybatis.type-handlers-package}")
    private String typeHandlersPackage;

    /* 配置mapper的扫描，找到所有的mapper.xml映射文件 */
    @Value("${mybatis.mapper-locations}")
    private String mapperLocations;

    /**
     * 获取数据源
     *
     * @return 数据源
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DruidDataSource dataSource() {
        return new DruidDataSource();
    }

    /**
     * 分页插件
     *
     * @return 返回值
     */
    @Bean
    public PageHelper pageHelper() {
        //组装翻页插件实体类
        PageHelper pageHelper = new PageHelper();
        //设置实体类属性
        Properties p = new Properties();
        p.setProperty("offsetAsPageNum", "true");
        p.setProperty("rowBoundsWithCount", "true");
        p.setProperty("reasonable", "true");
        pageHelper.setProperties(p);
        return pageHelper;
    }

    /**
     * 获取Session工厂
     *
     * @return 返回值
     */
    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean() {
        try {
            //创建SqlSession工厂
            SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
            sessionFactoryBean.setDataSource(dataSource());
            sessionFactoryBean.setVfs(SpringBootVFS.class);
            //读取配置
            sessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);
            sessionFactoryBean.setTypeHandlersPackage(typeHandlersPackage);
            //获取资源
            Resource[] resources = new PathMatchingResourcePatternResolver().getResources(mapperLocations);
            sessionFactoryBean.setMapperLocations(resources);
            //拦截器
            Interceptor[] plugins = new Interceptor[]{pageHelper()};
            sessionFactoryBean.setPlugins(plugins);
            return sessionFactoryBean.getObject();
        } catch (Exception e) {
            throw new MyException(ExceptionEnum.SESSIONFACTORYEXCEPTION, e);
        }
    }

    /**
     * 事务处理
     *
     * @return 返回值
     */
    @Bean
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        //创建事物处理管理器
        return new DataSourceTransactionManager(dataSource());
    }
}
